import * as mars3d from 'mars3d'
import type { Map } from 'mars3d'
import mitt from 'mitt'

type MapOptions = {
  scene?: {
    center?: {
      lat: number
      lng: number
      alt: number
      heading: number
      pitch: number
    }
  }
  terrain?: {
    url: string
    show: boolean
  }
  basemaps?: Array<{
    name: string
    icon: string
    type: string
    layer: string
    show: boolean
  }>
  container?: string
}

export class MapEngine {
  private map: Map | null = null
  private options: MapOptions
  private emitter = mitt()

  constructor(config: MapOptions) {
    this.options = {
      scene: {
        center: { lat: 30.054604, lng: 108.885436, alt: 17036414, heading: 0, pitch: -90 },
      },
      terrain: {
        url: 'https://data.mars3d.cn/terrain',
        show: true,
      },
      basemaps: [
        {
          name: '天地图影像',
          icon: 'https://data.mars3d.cn/img/thumbnail/basemap/tdt_img.png',
          type: 'tdt',
          layer: 'img_d',
          show: true,
        },
      ],
      ...config,
    }
  }

  async initialize() {
    if (this.map) return

    try {
      this.map = new mars3d.Map(this.options.container || 'mapContainer', this.options)

      // 绑定事件
      this.map.on(mars3d.EventType.load, () => {
        this.emitter.emit('loaded')
      })

      this.map.on(mars3d.EventType.click, (event) => {
        this.emitter.emit('click', event)
      })

      await new Promise<void>((resolve) => {
        if (this.map) {
          this.map.on(mars3d.EventType.load, () => {
            resolve()
          })
        }
      })

    } catch (error) {
      console.error('Failed to initialize Mars3D:', error)
      throw error
    }
  }

  on(event: string, callback: (...args: any[]) => void) {
    this.emitter.on(event, callback)
  }

  getInstance(): Map | null {
    return this.map
  }

  destroy() {
    if (this.map) {
      this.map.destroy()
      this.map = null
    }
    this.emitter.all.clear()
  }
}
